package com.zyz.bookborrowing.servlet;

import com.zyz.bookborrowing.bean.Classes;
import com.zyz.bookborrowing.bean.Department;
import com.zyz.bookborrowing.service.*;
import com.zyz.bookborrowing.utils.Constant;
import com.zyz.bookborrowing.utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "classServlet", urlPatterns = "/classServlet")
public class ClassServlet extends HttpServlet {

    IClassService classService = new ClassServiceImpl();
    IDepartmentService departmentService = new DepartmentServiceImpl();
    IStudentService studentService = new StudentServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1. 获取请求的类型
        String type = req.getParameter(Constant.REQUEST_PARAMETER_TYPE);
//        2. 如果type不为空，那么根据type不同值做出不同操作
        if (StringUtils.isNotEmpty(type)){
            if (Constant.SERVLET_TYPE_QUERY.equals(type)){
                queryClass(req, resp);
            } else if (Constant.SERVLET_TYPE_SAVE.equals(type)){
                saveClass(req, resp);
            } else if (Constant.SERVLET_TYPE_UPDATE.equals(type)) {
                saveClass(req, resp);
            } else if (Constant.SERVLET_TYPE_DELETE.equals(type)) {
                deleteClass(req, resp);
            } else if (Constant.SERVLET_TYPE_QUERYBYID.equals(type)) {
                String id = req.getParameter("id");
                Classes classes = classService.queryById(Integer.parseInt(id));
                List<Department> list = departmentService.list(null);
                req.setAttribute("cls", classes);
                req.setAttribute("depts", list);
                req.getRequestDispatcher("/classes/classesUpdate.jsp").forward(req, resp);
            } else if ("queryAllDept".equals(type)){
//                查询所有院校信息
                List<Department> list = departmentService.list(null);
                req.setAttribute("depts", list);
                req.getRequestDispatcher("/classes/classesUpdate.jsp").forward(req, resp);
            } else {
                queryClass(req, resp);
            }
        } else {
            queryClass(req, resp);
        }
    }

    private void deleteClass(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
//        需要判断班级是否有学生，有学生就不能删除
        int count = studentService.queryByClsId(id);
        if (count > 0){
//            告诉浏览器当html处理（MIME类型：text 超文本标记语言）
            resp.setContentType("text/html;charset=UTF-8");
            PrintWriter writer = resp.getWriter();
//            <script type='text/javascript' >
//                    alert("当前班级还有学生，不能删除");
//            location.href='/classServlet?type=query'
//            </script>
            writer.println("<script type='text/javascript' >");
            writer.println("alert('当前班级还有学生，不能删除');");
            writer.println("location.href='/classServlet?type=query';");
            writer.println("</script>");
//            刷新
            writer.flush();
        } else {
            classService.deleteById(Integer.parseInt(id));
            resp.sendRedirect("/classServlet?type=query");
        }
    }

    private void saveClass(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Classes cls = new Classes();
        String id = req.getParameter("id");
        cls.setClassName(req.getParameter("className"));
        cls.setClassDesc(req.getParameter("classDesc"));
        String deptId = req.getParameter("deptId");
        cls.setDeptId(Integer.parseInt(deptId));
        if (StringUtils.isEmpty(cls.getDeptName()) && cls.getDeptId() != null){
            Department department = departmentService.queryById(cls.getDeptId());
            cls.setDeptName(department.getDepartment());
        }
        Integer count = -1;

        if (id == null || id.equals("")){
//                count:影响的行数
            count = classService.saveClasses(cls);
        } else {
            cls.setId(Integer.parseInt(id));
            count = classService.updateClasses(cls);
        }
        if (count > 0){
//                    表示增/更成功,再做一次查询操作
            resp.sendRedirect("/classServlet?type=query");
        } else {
//                    插入失败
            System.out.println("插入失败...");
//                    跳转失败页面
        }
    }

    private void queryClass(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Classes> list = classService.list(null);
        req.setAttribute("list", list);
        req.getRequestDispatcher("/classes/classes.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }
}
